package com.mall.utils;

import cn.hutool.core.util.StrUtil;

import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

/**
 * @Author: Sam
 * @Date: 2022/9/13 16:36
 * @Description: sql注入工具类
 */
public class SqlInjUtil {

    private final static String REGEX = "%|select|update|delete|insert|drop|truncate|create|alter|" +
            "declare|grant|use|or|union|and|execute|exec|xp_cmdshell|call|information_schema.columns|shutdown";

    private final static List<String> SQL_INJ_WORD_POOL = Arrays.asList(REGEX.split("\\|"));

    /**
     * sql关键词注入检测
     *
     * @param param 需要检测的串
     * @return 注入字符
     */
    public static String sqlValidate(String... param) {
        for (String str : param) {
            if (StrUtil.isEmpty(str)) {
                return null;
            }
            str = str.trim().toLowerCase();//统一转为小写
            StringTokenizer tokenizer = new StringTokenizer(str);
            while (tokenizer.hasMoreTokens()) {
                String key = tokenizer.nextToken();
                //匹配是否有sql注入
                if (SQL_INJ_WORD_POOL.contains(key)) {
                    return key;
                }
            }
        }
        return null;
    }

}
